package com.invoicerecognition.backend.service.impl.student;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.invoicerecognition.backend.mapper.StudentMapper;
import com.invoicerecognition.backend.model.dto.Student;
import com.invoicerecognition.backend.model.dto.User;
import com.invoicerecognition.backend.service.student.UpdateStudentInfoService;
import com.invoicerecognition.backend.service.impl.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UpdateStudentInfoServiceImpl implements UpdateStudentInfoService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public Map<String, String> UpdateStudentInfo(Map<String, String> data) {

        String studentId = data.get("studentId");
        String name = data.get("name");
        String grade = data.get("grade");

        Map<String, String> resp = new HashMap<>();

        if (studentId.isEmpty()) {
            resp.put("error_message", "学号不能为空");
            return resp;
        }

        if (studentId.length() > 20) {
            resp.put("error_message", "学号长度超过限制");
            return resp;
        }

        if (name.isEmpty()) {
            resp.put("error_message", "姓名不能为空");
            return resp;
        }

        if (name.length() > 10) {
            resp.put("error_message", "姓名长度超过限制");
            return resp;
        }

        if (grade.isEmpty()) {
            resp.put("error_message", "班级不能为空");
            return resp;
        }

        if (grade.length() > 10) {
            resp.put("error_message", "班级长度超过限制");
            return resp;
        }

        UsernamePasswordAuthenticationToken authentication =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();

        UserDetailsImpl loginUser = (UserDetailsImpl) authentication.getPrincipal();
        User user = loginUser.getUser();

        int userId = user.getId();
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Student student = studentMapper.selectOne(queryWrapper);
        if (student == null) {
            student = new Student(null, userId, studentId, name, grade);
            studentMapper.insert(student);
        }
        else {
            student.setStudentId(studentId);
            student.setName(name);
            student.setGrade(grade);
            studentMapper.updateById(student);
        }

        resp.put("error_message", "success");
        resp.put("studentId", studentId);
        resp.put("name", name);
        resp.put("grade", grade);
        return resp;
    }
}
